package com.thinvent.remotepassword.interceptor;

import com.thinvent.remotepassword.entity.WikiUser;
import com.thinvent.remotepassword.util.AuthStorage;
import com.thinvent.remotepassword.util.JwtUtil;
import com.thinvent.remotepassword.util.TokenContext;
import com.thinvent.remotepassword.util.UserContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyLoginInterception implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(AuthStorage.TOKEN_KEY);
        if(StringUtils.hasLength(token)){
            WikiUser wikiUser = JwtUtil.checkToken(token);
            if(wikiUser != null && wikiUser.getId()!= null){
                AuthStorage.setUser(token,wikiUser);
                // 将用户id放入threadlocal中
                UserContext userContext = new UserContext();
                userContext.put(wikiUser.getId());
                // 将用户token放入私有变量
                TokenContext tokenContext = new TokenContext();
                tokenContext.put(token);
                return true;
            }
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("请先登录!");
        return false;
    }
    /**
     * 判断请求的URI是否属于不需要拦截的页面
     * @param uri 请求的URI
     * @return 是否属于不需要拦截的页面
     */
    private boolean isCludedPage(String uri) {

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AuthStorage.clearUser();
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}

